package com.example.esp8266.Equipment.Task_Fragment;

import android.annotation.SuppressLint;
import android.content.Context;
import android.content.SharedPreferences;
import android.os.Bundle;

import androidx.fragment.app.Fragment;
import androidx.fragment.app.FragmentManager;
import androidx.fragment.app.FragmentTransaction;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.TextView;

import com.example.esp8266.Init.ESP8266_APP;
import com.example.esp8266.Library.RoomLib.AppDatabase;
import com.example.esp8266.Library.RoomLib.Dao_Interface.TaskDao;

import com.example.esp8266.Library.RoomLib.Task;
import com.example.esp8266.Library.RoomLib.TaskAdapter;
import com.example.esp8266.Library.RoomLib.VerticalSpaceItemDecoration;
import com.example.esp8266.R;

import java.util.ArrayList;
import java.util.List;

public class TaskList_Fragment extends Fragment {
    private View root;
    private int taskGroupId;
    private String back_info,task_group_name_bundle;
    private RecyclerView recyclerView;
    private TaskAdapter adapter;
    private TaskDao taskDao;
    private AppDatabase database;

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        // 获取传递的数据
        Bundle args = getArguments();
        if (args != null) {
            taskGroupId = args.getInt("task_groupId", -1); // 获取任务组ID
            task_group_name_bundle = args.getString("task_groupName", null); // 获取任务组名字
            back_info = args.getString("back_info", "MainControlFragment"); // 返回上一层标识
        }

        // 检查 getActivity() 是否返回的对象为非空
        if (getActivity() != null) {
            // 获取 SharedPreferences 对象
            SharedPreferences sharedPreferences = getActivity().getSharedPreferences("my_prefs", Context.MODE_PRIVATE);
            SharedPreferences.Editor editor = sharedPreferences.edit();
            editor.putInt("task_groupId",taskGroupId);
            editor.putString("task_groupName",task_group_name_bundle);
            editor.putString("previous_page", back_info);
            editor.apply();
        } else {
            Log.e("TaskList_Fragment", "getActivity() returned null");
            // 可以选择在这里处理 getActivity() 返回 null 的情况，例如显示错误信息或采取其他操作
        }

    }

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
        root = inflater.inflate(R.layout.task_list_fragment, container, false);

        // 获取数据库实例
        database = ESP8266_APP.getInstance().getDatabase();
        taskDao = database.taskDao();

        recyclerView = root.findViewById(R.id.task_list_recycler_view);
        recyclerView.setLayoutManager(new LinearLayoutManager(requireContext()));

        // 设置竖直间隔距离
        int spaceHeight = getResources().getDimensionPixelSize(R.dimen.recycler_view_item_space);
        recyclerView.addItemDecoration(new VerticalSpaceItemDecoration(spaceHeight));

        adapter = new TaskAdapter(new ArrayList<>(), requireContext());
        recyclerView.setAdapter(adapter);

        // 设置点击事件监听器
        adapter.setOnTaskEditListener(new TaskAdapter.OnTaskEditListener() {
            @Override
            public void onTaskEdit(Task task) {
                // 编辑任务的逻辑
            }
        });

        // 设置创建新任务按钮的点击事件监听器
        adapter.setOnTaskCreateListener(new TaskAdapter.OnTaskCreateListener() {
            @Override
            public void onCreateNewTask() {
                // 新建任务的逻辑
                Bundle args = new Bundle();
                args.putString("back_info", "TaskList_Fragment");
                args.putInt("task_groupId", taskGroupId); // 传递任务组ID
                args.putString("task_groupName", task_group_name_bundle); // 传递任务组名称

                // 处理点击事件，切换到 TaskList_Fragment 并传递任务组ID
                TaskCreate taskListFragment = new TaskCreate();
                taskListFragment.setArguments(args);
                replaceFragment(taskListFragment);
            }
        });

        // 查询数据库并更新任务指列表
        loadTasks(taskGroupId);

        return root;
    }

    @SuppressLint("SetTextI18n")
    private void loadTasks(int taskGroupId) {
        new Thread(() -> {
            // 在这里根据任务组ID从数据库查询任务
            List<Task> tasks = taskDao.getTasksByGroupId(taskGroupId);

            requireActivity().runOnUiThread(() -> {
                // 更新UI，例如RecyclerView的Adapter
                adapter.setTasks(tasks);
                TextView group_name = root.findViewById(R.id.task_list_task_group_name);
                group_name.setText("("+task_group_name_bundle+")");
            });
        }).start();
    }

    /** 动态切换视图*/
    private void replaceFragment(Fragment fragment) {
        if (getActivity() != null) {
            FragmentManager fragmentManager = getActivity().getSupportFragmentManager();
            FragmentTransaction transaction = fragmentManager.beginTransaction();
            transaction.replace(R.id.control_fragment_view, fragment);
            transaction.commit();
        }
    }
}